#!/usr/bin/env bash
set -euo pipefail

# Generator contract:
#  - positional $1: destination path to write (e.g. scripts/analysis_sales.py)
#  - positional $2: human-friendly task name (will replace __TASK_NAME__)
#  - optional flags: --force (overwrite), --standalone (embed full bootstrap)
# Output: writes the generated python script to DEST and makes it executable.

if [[ "$#" -lt 2 ]]; then
  echo "Usage: $0 <dest_path> \"Task Name\" [--force] [--standalone]"
  echo "Example: $0 scripts/my_analysis.py \"销售分析\" --force"
  exit 2
fi

DEST="$1"
TASK_NAME="$2"
FORCE_FLAG=""
STANDALONE_FLAG=""  # default: do NOT embed snippet; use lightweight import header
shift 2
for arg in "$@"; do
  case "$arg" in
    --force) FORCE_FLAG="--force" ;;
    --standalone) STANDALONE_FLAG="--standalone" ;;
    --no-standalone|--no-embed) STANDALONE_FLAG="" ;;
    *) echo "Unknown flag: $arg"; exit 2 ;;
  esac
done

TEMPLATE_DIR="$(cd "$(dirname "$0")/../templates" && pwd)"
TEMPLATE_FILE="$TEMPLATE_DIR/template_script.py"
IMPORT_HEADER="$TEMPLATE_DIR/import_header.py"
STANDALONE_TEMPLATE="$TEMPLATE_DIR/standalone_template.py"
BOOTSTRAP_SNIPPET="$TEMPLATE_DIR/bootstrap_snippet.py"

if [[ -e "$DEST" && "$FORCE_FLAG" != "--force" ]]; then
  echo "Destination $DEST exists; use --force to overwrite."
  exit 1
fi

mkdir -p "$(dirname "$DEST")"

if [[ "$STANDALONE_FLAG" == "--standalone" ]]; then
  # embed full bootstrap snippet and standalone template
  cat "$BOOTSTRAP_SNIPPET" > "$DEST"
  printf "\n# ---- embedded standalone template starts here ----\n\n" >> "$DEST"
  cat "$STANDALONE_TEMPLATE" >> "$DEST"
else
  # default: create a small header that imports shared helpers, then append standalone body
  cat "$IMPORT_HEADER" > "$DEST"
  printf "\n# ---- standalone template body starts here ----\n\n" >> "$DEST"
  cat "$STANDALONE_TEMPLATE" >> "$DEST"
fi

# replace placeholder with the task name
awk -v name="$TASK_NAME" '{ gsub(/__TASK_NAME__/, name); print }' "$DEST" > "$DEST.tmp" && mv "$DEST.tmp" "$DEST"

# (输出文件名由脚本作者在模板中控制，生成器不替换输出文件名占位符)
chmod +x "$DEST"
echo "Created $DEST (standalone=${STANDALONE_FLAG:-no})"
